package com.kdtech.analyse.Bbs;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;
import com.kdtech.utils.StringUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.analyse.AnalyseNews;

/**
 *  站长论坛 解析类
 *
 * @author Chase
 *
 */
public class ChinazBbsAnalyse implements AnalyseNews {

	

	
	public boolean isDetailPage(String url) {
		boolean bRet = false;
		String[] regex = {
				"http://bbs.chinaz.com/thread-[0-9]*-[1]-1.html"
				};
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {

		String url = urlMeta.getUrl();
		/**
		 * 判断是否为详细页，不是详细页面直接返回空
		 */
		if (!isDetailPage(url)) {
			System.err.println("不符合规则");
		}

		String html = urlMeta.getHtml();

		/*
		 * 定义新闻实体需要的字段
		 */
		String title = null;
		String dateStr = null;
		String content = null;
		String author = null;
		Long dateLong = null;
		String commentNum = null;
		String clickNum = null;

		Document doc = Jsoup.parse(html);
		title = doc.select("div.cz-box-t h1").text();// 标题
		if (StringUtils.isNullOrEmpty(title)) {
			title = doc.select("h3.postwrap-title").text();// 标题
		}

		dateStr = doc.select(".cz-box-meta small span").last().text();
		dateLong = DateUtils.matchDate(dateStr);// 时间

		content = HtmlCleaner.getContentHtml(url, doc.select(".pcb").first());

		author = doc.select(".cz-box-meta small span").first().select("a").text();
		

		clickNum = doc.select(".t-reply").parents().first().text(); //点击数
		if (clickNum.indexOf(" ") != -1) {
			String[] split = clickNum.split(" ");
			if (split.length>0) {
				clickNum = split[0];
				if (split.length>1) {
					commentNum = split[1];//评论数
				}
			}
		}
		NewsMeta meta = new NewsMeta();
		meta.setTitle(title);
		meta.setContent(content);
		meta.setAuthor(author);
		meta.setUrl(url);
		meta.setType(4);
		meta.setClickNum(NumberUtils.parseInt(clickNum));
		meta.setCommentNum(NumberUtils.parseInt(commentNum));
		meta.setDate(dateLong);

		/**
		 * 解析用于更新的地址
		 */
		String updateUrl= url;
		meta.setUpdateUrl(updateUrl);
		return meta;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		if(meta!=null){
			String updateUrl = meta.getUpdateUrl();
			if(StringUtils.isNotBlank(updateUrl)){
				UrlMeta urlMeta  = CrawlHTML.responseToURL(updateUrl);
				return parserHtml(urlMeta);
			}
		}
		return null;
	}



	
}
